package org.zjx.server.session;

import lombok.Getter;

import java.io.DataOutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class SessionManager {
    private final Map<String, ClientSession> sessions = new ConcurrentHashMap<>();
    private final Map<String, String> clientIdToSession = new ConcurrentHashMap<>();

    @Getter
    private static final SessionManager instance = new SessionManager();

    public ClientSession createSession(Socket socket, DataOutputStream outputStream) {
        String sessionId = generateSessionId(socket);
        ClientSession session = new ClientSession(sessionId, socket, outputStream);
        sessions.put(sessionId, session);
        return session;
    }

    public void removeSession(String sessionId) {
        ClientSession session = sessions.remove(sessionId);
        if (session != null) {
            session.setActive(false);
            if (session.getClientId() != null) {
                clientIdToSession.remove(session.getClientId());
            }
        }
    }

    public ClientSession getSessionByClientId(String clientId) {
        String sessionId = clientIdToSession.get(clientId);
        if (sessionId == null) return null;

        ClientSession session = sessions.get(sessionId);
        // 验证会话有效性
        if (session != null && session.isActive() && session.getClientId() != null
                && session.getClientId().equals(clientId)) {
            return session;
        }

        // 无效会话，清理映射
        clientIdToSession.remove(clientId);
        return null;
    }

    public void bindClientToSession(String clientId, String sessionId) {
        // 如果 clientId 已存在，先解除旧绑定
        if (clientIdToSession.containsKey(clientId)) {
            String oldSessionId = clientIdToSession.get(clientId);
            ClientSession oldSession = sessions.get(oldSessionId);
            if (oldSession != null) {
                oldSession.setClientId(null); // 清除旧会话的 clientId
            }
        }

        // 创建新绑定
        clientIdToSession.put(clientId, sessionId);

        // 更新会话的 clientId
        ClientSession session = sessions.get(sessionId);
        if (session != null) {
            session.setClientId(clientId);
        }
    }

    public Map<String, ClientSession> getAllSessions() {
        return Collections.unmodifiableMap(sessions);
    }

    private String generateSessionId(Socket socket) {
        return socket.getInetAddress().getHostAddress() + ":" + socket.getPort() + "-" + System.currentTimeMillis();
    }
}